package cn.cqie.frame.service.impl;

import cn.cqie.frame.bo.query.QueryClassBo;
import cn.cqie.frame.entity.Clazz;
import cn.cqie.frame.mapper.ClazzMapper;
import cn.cqie.frame.service.ClazzService;
import cn.cqie.frame.utils.AssertUtil;
import cn.cqie.frame.utils.MyPageHelper;
import cn.cqie.frame.vo.ClassVo;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author XYHL
 * @since 2021-10-09
 */
@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private ClazzService clazzService;

    /**
     * 新增or更新班级信息
     * @param bo
     * @return
     */
    @Override
    public Clazz saveOrUpdateClass(Clazz bo) {
        LocalDateTime sysTime = LocalDateTime.now();
        bo.setCreateTime(sysTime);
        bo.setUpdateTime(sysTime);
        boolean insert = clazzService.saveOrUpdate(bo);
        AssertUtil.isTrue(insert, "插入/更新菜单失败");
        return BeanUtil.toBean(bo, Clazz.class);
    }

    /**
     * 分页查询班级信息
     * @param bo
     * @return
     */
    @Override
    public List<ClassVo> list(QueryClassBo bo) {
        MyPageHelper.startPage(bo);
        LambdaQueryWrapper<Clazz> lqw = new LambdaQueryWrapper<>();
        lqw.eq(bo.getKeywords()!=null,Clazz::getName,bo.getKeywords());
        List<Clazz> clazzes = baseMapper.selectList(lqw);
        return entity2Vo(clazzes);
    }

    /**
     * 删除班级信息
     * @param classId
     * @return
     */
    @Override
    public Boolean deleterClass(Integer classId) {
        boolean b = clazzService.removeById(classId);
        return b;
    }

    /**
     * 格式转换
     * @param collection
     * @return
     */
    private List<ClassVo> entity2Vo(List<Clazz> collection) {
        List<ClassVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, ClassVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<Clazz> page = (Page<Clazz>) collection;
            Page<ClassVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page, pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }
}
